package com.young.common.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 常用的ip工具
 */
public class IPUtil {

    //本机ip缓存,linux获取网卡配置缓慢(5S左右)
    private static String LOCAL_IP = null;

    /**
     * 获取本地IP地址
     * @return
     */
    public static String getLocalIp(){
        if(LOCAL_IP != null){
            return LOCAL_IP;
        }
        String ipAddress = "";
        InetAddress inet = null;
        try {
            inet = InetAddress.getLocalHost();
        } catch (UnknownHostException var4) {

        }
        if (inet != null){
            ipAddress = inet.getHostAddress();
            if(ipAddress != null && ipAddress.length() > 15 && ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
            LOCAL_IP = ipAddress;//计入缓存,方便下次使用
        }
        return ipAddress;
    }
}
